package xyz.liut.autolaunch;

import android.annotation.SuppressLint;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.ResolveInfo;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Build;
import android.util.Log;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import xyz.liut.logcat.L;

/**
 * app 启动
 * <p>
 * Create by liut on 20-10-27
 */
public class LaunchTool {

    private static final String TAG = "LaunchTool";

    @SuppressLint("SimpleDateFormat")
    public static void launch(Context context, String pkg, boolean byRoot) {
        L.i("", "");

        L.d(pkg);

        L.d("time = " + new SimpleDateFormat("MM-dd HH:mm:ss").format(new Date()));
        L.d("root = " + byRoot);
        L.d("isScreenOn = " + SystemUtils.isScreenOn(context));
        L.d("isLocked = " + SystemUtils.isLocked(context));
        L.d("isNetworkAvailable = " + isNetworkAvailable(context));

        // 当为支付宝时, 且使用root模式启动
        if (AliPayLaunch.ALIPAY_PKG.equals(pkg) && byRoot) {
            // 启动支付宝服务
            AliPayLaunch.launch(context);
            // 且在亮屏状态, 且没有被锁定
            if (SystemUtils.isScreenOn(context) && !SystemUtils.isLocked(context)) {
                return;
            }
        }

        String launchCls = doStartApplicationWithPackageName(context, pkg);
        if (launchCls == null) {
            L.e("launchByRoot: 无法找到启动类: " + pkg);
            return;
        }

        if (byRoot) {
            launchByRoot(pkg, launchCls);
        } else {
            launchByIntent(context, pkg, launchCls);
        }

    }

    private static void launchByIntent(Context context, String pkg, String cls) {
        Log.d(TAG, "launchByIntent() called with: pkg = [" + pkg + "], cls = [" + cls + "]");

        Intent intent = new Intent();
        intent.setPackage(pkg);
        intent.setComponent(new ComponentName(pkg, cls));
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

        try {
            context.startActivity(intent);
            L.i("launch success");
        } catch (Exception e) {
            L.e("launch failed", e);
        }
    }

    private static void launchByRoot(String pkg, String cls) {
        final String finalLaunchCls = cls.replace(pkg, "");

        new Thread() {
            @Override
            public void run() {
                ProcessUtil.Result result = ProcessUtil.exec("su -c am start -n " + pkg + "/" + finalLaunchCls);
                if (result != null) {
                    result.println();
                    L.i("launch result = " + (result.exitValue == 0));
                } else {
                    L.e("launch failed");
                }

            }
        }.start();

    }

    /**
     * 通过包名查找启动类
     */
    private static String doStartApplicationWithPackageName(Context context, String pkg) {
        // 通过包名获取此APP详细信息，包括Activities、services、versioncode、name等等
        PackageInfo packageinfo = null;
        try {
            packageinfo = context.getPackageManager().getPackageInfo(pkg, 0);
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (packageinfo == null) {
            return null;
        }

        // 创建一个类别为CATEGORY_LAUNCHER的该包名的Intent
        Intent resolveIntent = new Intent(Intent.ACTION_MAIN, null);
        resolveIntent.addCategory(Intent.CATEGORY_LAUNCHER);
        resolveIntent.setPackage(packageinfo.packageName);

        // 通过getPackageManager()的queryIntentActivities方法遍历
        @SuppressLint("QueryPermissionsNeeded")
        List<ResolveInfo> resolveInfoList = context.getPackageManager().queryIntentActivities(resolveIntent, 0);
        for (ResolveInfo resolveInfo : resolveInfoList) {
            Log.d(TAG, "resolveInfo:" + resolveInfo);
        }
        ResolveInfo resolveinfo = resolveInfoList.iterator().next();
        if (resolveinfo != null) {
            return resolveinfo.activityInfo.name;
        }
        return null;
    }


    /**
     * 检查网络是否可用
     */
    public static boolean isNetworkAvailable(Context context) {
        ConnectivityManager manager = (ConnectivityManager) context
                .getApplicationContext()
                .getSystemService(Context.CONNECTIVITY_SERVICE);

        if (manager == null) {
            return false;
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            NetworkInfo networkinfo = manager.getActiveNetworkInfo();
            return networkinfo != null && networkinfo.isAvailable();
        }
        return true;
    }

}
